/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package PacketHandling;

import Client.Client;
import com.esotericsoftware.kryonet.Connection;
import horizon.entity.Player;
import horizon.map.Chunk;
import horizon.network.ChunkEncoder;
import horizon.network.Packet;
import horizon.network.Packet.PKT_TYPE;
import horizon.space.Planet;
import GameManager.Universe;
import horizon.entity.Entity;
import horizon.util.Vector2;
import java.util.Collection;
import java.util.HashMap;
import java.util.StringTokenizer;

/**
 *
 * @author J_Laptop
 */
public class PacketParser {

    String playerName;
    Connection c;
    Packet packet;

    public PacketParser(Packet p, Connection c) {

        packet = p;
        this.c = c;
        playerName = p.auth;

      
        
        switch (classifyPacket()) {

            case CL_REG:

                handleRegistrationPacket();

                break;

            case CL_LOGIN:

                handleLoginPacket();

                break;
            case CL_DATA:

                handleHeader();

                break;
        }

        handleDataSector();

    }

    private PKT_TYPE classifyPacket() {

        return packet.header;

    }

    private void handleRegistrationPacket() {

        Player p;
        if (packet.auth.equals("")) {

            p = new Player("Guest " + PacketHandler.guestID++, null);

        } else {

            p = new Player(playerName, null);

        }
        
        Universe u = Universe.getInstance();
        u.addPlayer(p, "Earth");

        Packet t = new Packet();
        t.header = PKT_TYPE.SERV_REG;
        t._data += p.getId();

        c.sendTCP(t);
        PacketHandler.getInstance().sendNewEntity(p , c);
        PacketHandler.getInstance().clients.add(new Client(p.getId() , c.getID()));

    }

    private void handleLoginPacket() {
    }

    private void handleHeader() {

        playerName = packet.auth;

    }

    private void handleDataSector() {

        String data = packet._data;
        StringTokenizer str = new StringTokenizer(data, ";");

        while (str.hasMoreTokens()) {

            String t = str.nextToken();
            evaluateCommand(t);

        }

    }

    private void evaluateCommand(String t) {

        String opCode = t.substring(0, 3);

        switch (opCode) {

            case "mov":

                String s = t.substring(4, t.length());

                String pos = s.substring(0, s.lastIndexOf(":"));
                String mov = s.substring(s.lastIndexOf(":") + 1);
              
                float xPos = Float.valueOf(pos.substring(0, pos.lastIndexOf(",")));
                float yPos = Float.valueOf(pos.substring(pos.lastIndexOf(",") + 1));
               
                float xMov = Float.valueOf(mov.substring(0, mov.lastIndexOf(",")));
                float yMov = Float.valueOf(mov.substring(mov.lastIndexOf(",") + 1));
                
                Vector2 v = new Vector2(xMov , yMov);
                Vector2 position = new Vector2(xPos , yPos);
                Universe.getInstance().getEntity(playerName).setPosition(position);
                PacketHandler.getInstance().addMovementUpdate(playerName , new Vector2(xPos , yPos) ,v);
                
                
                break;
            case "req":

                String type = t.substring(4, t.length());

                if (type.equals("worldData")) {

                    sendWorldData();

                }

                break;
            case "cha":
                
                
                String l = t.substring(4, t.length());
                String text = playerName + ":" + l;
                String planet = Universe.getInstance().getLocation(playerName);
                Universe.getInstance().getPlanet(planet).messages.add(text);
                
                for(Entity e : Universe.getInstance().getPlanet(planet).getEntities()){
                    
                    if(e instanceof Player){
                        Player p = (Player) e;
                        for(Client c : PacketHandler.getInstance().clients){
                            
                            if(p.getId().equals(c.getPlayerName())){
                                
                                PacketHandler.getInstance().sendChat(c.getConnectionId(), text);
                                break;
                            }
                            
                        }
                        
                    }
                    
                }
                
                break;

        }

    }

    public void sendWorldData() {

        System.out.println("Searching for player named: " + playerName);

        String location = Universe.getInstance().getLocation(playerName);

        System.out.println("Searching for Planet named: " + location);

        Planet planet = Universe.getInstance().getPlanet(location);

        HashMap<Vector2, Chunk> chunks = planet.getChunks();

        Collection<Chunk> chunkList = (Collection<Chunk>) chunks.values();
        PacketHandler.getInstance().sendPacketNumber(c, chunkList.size() + 1);

        for (Chunk chunk : chunkList) {

            PacketHandler.getInstance().sendChunk(c, ChunkEncoder.encodeChunk(chunk));

        }

        PacketHandler.getInstance().sendEntityList(c, planet.getEntities());



    }
}
